package org.ihelpuoo.parser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.ihelpuoo.io.CharInputStream;
import org.ihelpuoo.io.StringBufferOutputStream;
import org.ihelpuoo.lang.LoaderException;
import org.ihelpuoo.lang.RenderException;

public abstract class AbstractTextEngine implements TextParser, TextRender
{

	public void render2(OutputStream ops) throws RenderException
	{
		try
		{
			Writer bw = new OutputStreamWriter(ops);
			render2(bw);
			bw.close();
		}
		catch (IOException e)
		{
			throw new RenderException(e);
		}
	}

	public void parse(InputStream ins) throws LoaderException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(ins));
		parse(br);
	}

	public void parse(CharSequence cs) throws LoaderException
	{
		parse(new CharInputStream(cs));
	}

	@Override
	public String toString()
	{
		try
		{
			StringBuffer sb = new StringBuffer();
			StringBufferOutputStream ops = new StringBufferOutputStream(sb);
			render2(ops);
			ops.close();
			return sb.toString();
		}
		catch (RenderException e)
		{
			return null;
		}
		catch (IOException e)
		{
			return null;
		}
	}

}
